﻿$(document).ready(function () {

    //INIT

    var PersonName;
    var arrPerson = [];
    var arrExpense = [];
    var arrPayment = [];
    var flag = 0;
    var expenseAttrValues = [];
    var forWhom = [];
    var strForWhom = "";
    var personAttributes = ["Row", "Person Name"];
    var expenseAttributes = ["Row", "Who Paid?", "Amount", "For Whom?"];
    var tableHeaderBind = function (tableName, headings) {
        var thead = $('#' + tableName + ' thead');
        var tbody = $('#' + tableName + ' tbody');
        var trhead = $('<tr>');
        thead.html('');
        tbody.html('');
        $.each(headings, function (i, prop) {
            $('<th>').html(prop).appendTo(trhead);
            thead.append(trhead);
        });
    }
    $("html,body").scrollTop(0);

    //PERSON MODAL

    $("#getStarted").click(function () {
        if (arrPayment.length == 0)
            tableHeaderBind("personTable", personAttributes);
        $('#addPerson').removeAttr('disabled');
    });

    $("#addPerson").click(function () {
        $("#personName").val('');
        $("#personModal").modal('show');
    });

    $('#personModal').on('shown.bs.modal', function () {
        $('#personName').focus();
    })

    $("#saveNextPersonModal").click(function () {
        PersonName = $("#personName")[0].value;
        if (PersonName.trim() != "") {
            arrPerson.push(PersonName);
            $("#personName").val('');
            populateTable("personTable", arrPerson);
            if (arrPerson.length >= 2)
                $("#enterExpense").removeAttr('disabled')
        } else {
            Validation(1, "alertModel");
        }
        $("#personName").focus();
    });

    $("#savePersonModal").click(function () {
        PersonName = $("#personName")[0].value;
        if (PersonName.trim() != "") {
            $("#savePersonModal").attr('data-dismiss', 'modal');
            arrPerson.push(PersonName);
            $("#personName").val('');
            populateTable("personTable", arrPerson);
            if (arrPerson.length >= 2) {
                //$("#addPerson").attr('disabled', 'disabled');
                $("#enterExpense").removeAttr('disabled');
            }
        } else {
            $("#savePersonModal").attr('data-dismiss', '');
            Validation(1, "alertModel");
            $("#personName").focus();
        }
    });

    $("#personDeleteSelected").click(function () {
        flag = 0;
        $.each($("#personTable :checkbox"), function (i, checkbox) {
            var $this = $(this);
            if (flag >= 1)
                i = i - flag;
            // $this will contain a reference to the checkbox   
            if ($this.is(':checked')) {
                // the checkbox was checked 
                var removedPerson = arrPerson.splice(i, 1);
                //numberofPerson = numberofPerson - 1;
                flag = flag + 1;
                if (arrExpense.length > 0) {
                    $.each(arrExpense, function (index, val) {
                        if (arrExpense[index][1].trim() == removedPerson[0].trim()) {
                            arrExpense.splice(index, 1);
                        }
                    });
                }
            }
        });
        populateTable("personTable", arrPerson);
        if (arrExpense.length > 0) {

        }
        if (arrPerson.length <= 1) {
            //$("#addPerson").removeAttr('disabled');
            $("#enterExpense").attr('disabled', 'disabled');
        }
        $("#personDeleteSelected").attr('disabled', 'disabled');
        //$("#addPerson").removeAttr('disabled');
    });

    $("#enterExpense").click(function () {
        if (arrExpense.length == 0)
            tableHeaderBind("expenseTable", expenseAttributes);
        else {
            forWhom = [];
            $("#expenseModal").find('input[type=radio]').remove();
            $("#expenseModal").find('input[type=checkbox]').remove();
            $("#expenseModal").find(".appendName").remove();
            $.each(arrPerson, function (i, person) {
                if (i == 0)
                    $("#expenseModal").find("#whoPaid").append('<input type="radio" name="whoPaid" checked="checked"/><span class=appendName style="padding-right: 10px"> ' + person + '</span>');
                else {
                    $("#expenseModal").find("#whoPaid").append('<input type="radio" name="whoPaid"/><span class=appendName style="padding-right: 10px"> ' + person + '</span>');
                }
                $("#expenseModal").find("#forWhom").append('<input type="checkbox" name="forWhom" checked="checked"/> <span class=appendName style="padding-right: 10px">' + person + '</span>');
            });
            $.each($('input[name=forWhom]:checked', '#expenseForm').next('span.appendName'), function (i, text) {
                forWhom[i] = text.innerText;
            });
            $.each(arrExpense, function (index, arrVal) {
                arrExpense[index][3] = forWhom;
            });
            populateTable("expenseTable", arrExpense);
        }
        $("#addExpense").removeAttr('disabled');
    });

    // EXPENSE MODAL

    $('#expenseModal').on('shown.bs.modal', function () {
        $('#amount').focus();
    })

    $("#addExpense").click(function () {
        $("#expenseModal").find('input[type=radio]').remove();
        $("#expenseModal").find('input[type=checkbox]').remove();
        $("#expenseModal").find(".appendName").remove();
        $.each(arrPerson, function (i, person) {
            if (i == 0)
                $("#expenseModal").find("#whoPaid").append('<input type="radio" name="whoPaid" checked="checked"/><span class=appendName style="padding-right: 10px"> ' + person + '</span>');
            else {
                $("#expenseModal").find("#whoPaid").append('<input type="radio" name="whoPaid"/><span class=appendName style="padding-right: 10px"> ' + person + '</span>');
            }
            $("#expenseModal").find("#forWhom").append('<input type="checkbox" name="forWhom" checked="checked"/> <span class=appendName style="padding-right: 10px">' + person + '</span>');
        });
        $("#expenseModal").modal('show');
    });

    $("#saveNextExpenseModal").click(function () {
        forWhom = [];
        expenseAttrValues = [];
        expenseAttrValues[1] = $('input[name=whoPaid]:checked', '#expenseForm').next('span.appendName')[0].innerText.trim();
        expenseAttrValues[2] = $("#amount")[0].value.trim();
        $.each($('input[name=forWhom]:checked', '#expenseForm').next('span.appendName'), function (i, text) {
            forWhom[i] = text.innerText.trim();
        });
        expenseAttrValues[3] = forWhom;
        if (expenseAttrValues[2].trim() != "") {
            $("#saveExpenseModal").attr('data-dismiss', 'modal');
            arrExpense.push(expenseAttrValues);
            $("#amount").val('');
            populateTable("expenseTable", arrExpense);
            $("#fixedExpense").removeAttr('disabled');
        } else {
            $("#saveExpenseModal").attr('data-dismiss', '');
            Validation(1, "expenseAlertModal");
            $("#amount").focus();
            return false;
        }
        $('#amount').focus();
    });

    $("#saveExpenseModal").click(function () {
        forWhom = [];
        expenseAttrValues = [];
        expenseAttrValues[1] = $('input[name=whoPaid]:checked', '#expenseForm').next('span.appendName')[0].innerText.trim();
        expenseAttrValues[2] = $("#amount")[0].value.trim();
        $.each($('input[name=forWhom]:checked', '#expenseForm').next('span.appendName'), function (i, text) {
            forWhom[i] = text.innerText.trim();
        });
        expenseAttrValues[3] = forWhom;
        if (expenseAttrValues[2].trim() != "") {
            $("#saveExpenseModal").attr('data-dismiss', 'modal');
            arrExpense.push(expenseAttrValues);
            $("#amount").val('');
            populateTable("expenseTable", arrExpense);
            $("#fixedExpense").removeAttr('disabled');
        } else {
            $("#saveExpenseModal").attr('data-dismiss', '');
            Validation(1, "expenseAlertModal");
            $("#amount").focus();
            return false;
        }
    });

    $("#expenseDeleteSelected").click(function () {
        flag = 0;
        $.each($("#expenseTable :checkbox"), function (i, checkbox) {
            var $this = $(this);
            if (flag >= 1)
                i = i - flag;
            // $this will contain a reference to the checkbox   
            if ($this.is(':checked')) {
                // the checkbox was checked 
                arrExpense.splice(i, 1);
                //numberofExpense = numberofExpense - 1;
                flag = flag + 1;
            }
        });
        populateTable("expenseTable", arrExpense);
        if (arrExpense.length == 0) {
            $("#fixedExpense").attr('disabled', 'disabled');
            $("#computePayment").attr('disabled', 'disabled');
        }
        $("#expenseDeleteSelected").attr('disabled', 'disabled');
    });

    //COMPUTE PAYMENT

    $("#computePayment").click(function () {
        computeExpense();
        computePayment("computePayementTable");
    });

    var computeExpense = function () {
        var arrTempExpense = arrExpense.slice(0);
        var bool = true;
        var individualTotal = 0;
        var total = 0;
        var totalExpenseCount = 0;
        var name = "";
        arrPayment = [];
        var expenseCount = 1;
        var balance = 0;
        var perHead = 0;
        var totalBalance = 0;
        var arrPaymentCount = -1;
        var exist = true;
        $.each(arrTempExpense, function (i, val) {
            total = total + Math.round(parseInt(val[2]));
        });
        perHead = Math.round(total / arrPerson.length);
        for (var j = 0 ; j < arrTempExpense.length; j++) {
            bool = true;
            expenseCount = 1;
            arrPaymentCount = arrPaymentCount + 1;
            for (var i = j + 1 ; i < arrTempExpense.length; i++) {
                if (arrTempExpense[j][1] == arrTempExpense[i][1]) {
                    bool = false;
                    expenseCount = expenseCount + 1;
                    name = arrTempExpense[j][1];
                    if (expenseCount == 2)
                        individualTotal = Math.round(parseInt(arrTempExpense[j][2])) + Math.round(parseInt(arrTempExpense[i][2]));
                    else
                        individualTotal = individualTotal + Math.round(parseInt(arrTempExpense[i][2]));
                }
            }

            if (bool) {
                name = arrTempExpense[j][1];
                balance = Math.round(parseInt(arrTempExpense[j][2])) - perHead;
                arrPayment[arrPaymentCount] = [name, 1, Math.round(arrTempExpense[j][2]), balance]
            } else {
                balance = individualTotal - perHead;
                arrPayment[arrPaymentCount] = [name, expenseCount, individualTotal, balance]
            }
            for (var l = 0 ; l < arrTempExpense.length; l++) {
                if (arrTempExpense[l][1] == name) {
                    arrTempExpense.splice(l, 1);
                    l = l - 1;
                }
            }
            j = j - 1;
        }
        $.each(arrPerson, function (index, person) {
            $.each(arrPayment, function (i, payVal) {
                var val = payVal.indexOf(person);
                if (val == 0) {
                    exist = false;
                    return false;
                } else {
                    exist = true;
                }
            });
            if (exist) {
                balance = -perHead;
                arrPayment[arrPayment.length] = [person, 0, 0, balance];
            }
        });
        $.each(arrPayment, function (i, val) {
            totalBalance = totalBalance + parseInt(val[3]);
            totalExpenseCount = totalExpenseCount + parseInt(val[1]);
        });

        if (arrPayment.length > 0) {
            arrPayment[arrPayment.length] = ["Total", totalExpenseCount, total, totalBalance]
            populateComputeExpenseTable("computeExpenseTable", arrPayment)
        }
    }

    var computePayment = function (tableName) {
        var arrAdjustment = [];
        var tbody = $('#' + tableName + ' tbody').html('');
        var arrNegative = [];
        var arrPositive = [];

        $.each(arrPayment, function (i, val) {
            if (i < arrPayment.length - 1) {
                if (val[3] < 0)
                    arrNegative.push([val[0], val[3] * (-1)]);
                else
                    arrPositive.push([val[0], val[3]]);
            }
        });
        arrNegative.sort(function (element_a, element_b) {
            return element_a[1] - element_b[1];
        });
        arrPositive.sort(function (element_a, element_b) {
            return element_a[1] - element_b[1];
        });
        arrAdjustment = arrNegative.concat(arrPositive);

        for (var i = 0 ; i < arrAdjustment.length; i++) {
            if (arrAdjustment[arrAdjustment.length - 1][1] > 0) {
                if (arrAdjustment[arrAdjustment.length - 1][1] < arrAdjustment[i][1]) {
                    arrAdjustment[i][1] = arrAdjustment[i][1] - arrAdjustment[arrAdjustment.length - 1][1];
                    populateComputePaymentTable(tableName, arrAdjustment[i][0], arrAdjustment[arrAdjustment.length - 1][1], arrAdjustment[arrAdjustment.length - 1][0]);
                    arrAdjustment.splice(arrAdjustment.length - 1, 1);
                } else {
                    populateComputePaymentTable(tableName, arrAdjustment[i][0], arrAdjustment[i][1], arrAdjustment[arrAdjustment.length - 1][0]);
                    arrAdjustment[arrAdjustment.length - 1][1] = arrAdjustment[arrAdjustment.length - 1][1] - arrAdjustment[i][1];
                    arrAdjustment.splice(i, 1);
                }
                i = i - 1;
            }
        }
    }

    //FIXED EXPENSES

    $('#fixedExpenseModal').on('shown.bs.modal', function () {
        $('#cook').focus();
    });

    $("#fixedExpense").click(function () {
        $("#fixedExpenseModal").modal('show');
    });

    $("#saveFixedExpenseModal").click(function () {
        $("#computePayment").removeAttr('disabled');
        $('#ck').html($('#cook')[0].value.trim());
        $('#md').html($('#maid')[0].value.trim());
        $('#hr').html($('#houseRent')[0].value.trim());
        var ttl = parseInt($('#cook')[0].value.trim()) + parseInt($('#maid')[0].value.trim()) + parseInt($('#houseRent')[0].value.trim());
        $('#ttl').html(ttl);
        $('#ph').html(Math.round(ttl / arrPerson.length));
    });

    //COMMON

    $(document).on("change", 'input[type=checkbox]', function () {
        $.each($("input[type=checkbox]"), function (i, checkbox) {
            var $this = $(this);
            // $this will contain a reference to the checkbox   
            var id = $this.closest('.container').parent().attr('id');
            if ($this.is(':checked')) {
                // the checkbox was checked 
                $("#" + id + "DeleteSelected").removeAttr('disabled');
                return false;
            } else {
                // the checkbox was unchecked
                $("#" + id + "DeleteSelected").attr('disabled', 'disabled');
            }
        });
    });

    var populateComputePaymentTable = function (tableName, firstName, firstValue, secondName) {
        var tbody = $('#' + tableName + ' tbody');
        var trbody = $('<tr>');
        $('<td style="padding: 0 5px ">').html(firstName).appendTo(trbody);
        $('<td style="padding: 0 5px ">').html('<input type="checkbox"/>').appendTo(trbody);
        $('<td style="padding: 0 50px; width: 0px; background: url(../img/payment-arrow.gif) no-repeat left center;">').appendTo(trbody);
        $('<td style="padding: 0 5px ">').html(firstValue).appendTo(trbody);
        $('<td style="padding: 0 50px; width: 0px; background: url(../img/payment-arrow.gif) no-repeat right center;">').appendTo(trbody);
        $('<td style="padding: 0 5px ">').html(secondName).appendTo(trbody);
        tbody.append(trbody);
    };

    var populateComputeExpenseTable = function (tableName, payement) {

        var tbody = $('#' + tableName + ' tbody').html('');
        $.each(payement, function (i, val) {
            var trbody = $('<tr>');
            $('<td>').html(val[0]).appendTo(trbody);
            $('<td>').html(val[1]).appendTo(trbody);
            $('<td>').html(val[2]).appendTo(trbody);
            $('<td>').html(val[3]).appendTo(trbody);
            tbody.append(trbody);
        });
    }

    var populateTable = function (tableName, arrValue) {
        var tbody = $('#' + tableName + ' tbody').html('');
        $.each(arrValue, function (index, val) {
            strForWhom = "";
            var tr = $('<tr>');
            $('<td>').html(index + 1).append("<div style='float:left; text-align: center'><input type='checkbox' /></div>").appendTo(tr);
            if (tableName == "personTable") {
                $('<td>').html(val).appendTo(tr);
            } else {
                $('<td>').html(val[1]).appendTo(tr);
                $('<td>').html(val[2]).appendTo(tr);
                $.each(val[3], function (index, value) {
                    strForWhom = strForWhom + ", " + value;
                });
                strForWhom = strForWhom.slice(2);
                $('<td>').html(strForWhom).appendTo(tr);
            }
            tbody.append(tr);
        });
    };

    var Validation = function (a, id) {
        if (a == "1") {
            $("#" + id).html("<strong>Error!</strong> Cannot be blank.");
            $("#" + id).slideDown("slow");
            $('#' + id).delay(3000).fadeOut();
        }
        if (a == "2") {
            $("#" + id).html("<strong>Error!</strong> Please provide correct input. <br><strong>NOTE:</strong> Only Numbers separated with single comma are allowed.");
            $("#" + id).slideDown("slow");
            $('#' + id).delay(3000).fadeOut();
            //alert("Please provide correct input \nNOTE: Only single comma separated numbers are allowed.");
        }
    };

});